<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="file" id="fileEle">
</body>
<script>
    const fileEle = document.querySelector("#fileEle")
    fileEle.addEventListener("change", (e) => {
        const file = e.target.files[0]
        const chunks = chunkFun(file)
        uploadFile(chunks)
    })

    // 文件分片
    function chunkFun(file, size = 1024 * 1024 * 2) {
        let chunks = []
        for (let i = 0; i < file.size; i += size) {
            chunks.push(file.slice(i, i + size))
        }
        return chunks
    }
    // 文件发送
    function uploadFile(chunks) {
        let list = []
        chunks.forEach((chunk, index) => {
            const formData = new FormData()
            formData.append("id", index)
            formData.append("total", chunks.length)
            formData.append("fileName", "跳舞")
            formData.append("file", chunk)
            list.push(fetch("http://localhost:3000/upload", {
                method: "POST",
                body: formData
            }))
        })
        Promise.all(list).then(res => {
            fetch('http://127.0.0.1:3000/uploadEnd', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    fileName: '跳舞',
                })
            }).then(res=>res.json()).then(res=>{
                alert(res.msg)
                fileEle.value = null
            })
        })
    }
</script>

</html>